package jin.chen.service.impl;

import jin.chen.mapper.TreeBasicMapper;
import jin.chen.pojo.TreeBasicPojo;
import jin.chen.service.TreeBasicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
public class TreeBasicServiceImpl implements TreeBasicService {

    @Autowired
    private TreeBasicMapper treeBasicMapper;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<TreeBasicPojo> queryAllRoot() {
        Example example = new Example(TreeBasicPojo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("type", 1);
        return treeBasicMapper.selectByExample(example);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<TreeBasicPojo> queryAllSubById(Integer id) {
        Example example = new Example(TreeBasicPojo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("fatherId", id);
        return treeBasicMapper.selectByExample(example);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void deleteById(Integer id, boolean isParentRoot) {
        Example example = new Example(TreeBasicPojo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", id);
        if(isParentRoot){
            criteria.orEqualTo("fatherId", id);
        }
        treeBasicMapper.deleteByExample(example);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void modifyName(Integer id, String newName) {
        Example example = new Example(TreeBasicPojo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", id);
        TreeBasicPojo pojo = new TreeBasicPojo();
        pojo.setName(newName);
        treeBasicMapper.updateByExampleSelective(pojo, example);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void createNode(TreeBasicPojo pojo, Integer id) {
        Example example = new Example(TreeBasicPojo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", id);
        TreeBasicPojo fatherPojo = treeBasicMapper.selectOneByExample(example);
        pojo.setCreateTime(new Date());
        pojo.setUpdateTime(new Date());
        pojo.setType(fatherPojo.getType() + 1);
        treeBasicMapper.insertSelective(pojo);
    }
}
